﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using System.Windows.Forms;
using System.IO;
using SharedLib.WinFormMVCFramework.ExceptionHandling;
using System.Threading;

namespace TracyGUI.ExceptionHandling
{
    abstract public class AbstractUIExceptionHandler
    {
        public AbstractUIExceptionHandler(NameValueCollection ignore)
        {
        }

        public virtual Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            ShowThreadExceptionDialog(exception, handlingInstanceId);
            return exception;
        }

        protected abstract string DialogTitle { get; }
        private static int _messageShown = 0;
        // Creates the error message and displays it.
        private void ShowThreadExceptionDialog(Exception ex, Guid handlingInstanceId)
        {

            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);

            SimpleExceptionFormatter formatter = new SimpleExceptionFormatter(writer, ex, handlingInstanceId);
            // Format the exception.
            formatter.Format();

            string message = FormatMessage(sb.ToString(), handlingInstanceId);

            if (Interlocked.Exchange(ref _messageShown, 1) == 0)
            {
                ExceptionForm.Show(message, DialogTitle);
                Interlocked.Exchange(ref _messageShown, 0);
            }
        }

        protected abstract string FormatMessage(string message, Guid handlingInstanceId);
    }

}
